import {
  TODO_ADD,
  TODO_CHECKALL,
  TODO_DEL,
  TODO_UPDATE,
} from '../action/actionType';

const initState = {
  list: [
    { id: 1, name: '学习vue2', done: true },
    { id: 2, name: '学习vue3', done: true },
    { id: 3, name: '学习react', done: false },
  ],
};

// 1. src/store/reducer/todo.js reducer函数
export default function todoReducer(state = initState, { type, payload }) {
  console.log('进入 todoReducer 了 -----> ', type, payload);
  switch (type) {
    case TODO_UPDATE:
      return {
        ...state,
        list: state.list.map((item) => {
          return {
            ...item,
            // 传过来的id和item.id 相同，说明需要改变 done，否则不用
            done: item.id === payload ? !item.done : item.done,
          };
        }),
      };

    case TODO_DEL:
      return {
        ...state,
        list: state.list.filter((item) => item.id !== payload),
      };

    case TODO_ADD:
      return {
        ...state,
        list: [payload, ...state.list],
      };

    case TODO_CHECKALL:
      return {
        ...state,
        list: state.list.map((item) => {
          return { ...item, done: payload };
        }),
      };
    default:
      return state;
  }
}
